package by.grsu.shedule.common;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;
import by.grsu.shedule.R;
import by.grsu.shedule.SettingsActivity;
import by.grsu.shedule.common.model.BaseModel;
import by.grsu.shedule.common.task.CommonAsyncTask;
import by.grsu.shedule.common.task.LoadArrayModelFromXMLAsyncTask;
import by.grsu.shedule.constants.ApplicationConstants;

public abstract class BaseArrayModelFromXmlAcivity<B extends BaseModel> extends
		DelegateActivity {

	private static final String TAG = BaseArrayModelFromXmlAcivity.class
			.getName();

	public abstract String getUrl();

	private static boolean isShowed = false;

	@Override
	public void startTasks() {
		if (isOnline()) {
			if (getUrl() == null) {
				showSettingsActivity();
			} else {
				if (isReload()) {
					executeActivityTasks(new LoadArrayModelFromXMLAsyncTask<B>(
							getUrl(), this));
				} else {
					if (getSheduleManager().isWeekSaved()) {
						restoreFromDB();
					} else {
						executeActivityTasks(new LoadArrayModelFromXMLAsyncTask<B>(
								getUrl(), this));
					}
				}
			}
		} else {
			if (getSheduleManager().isWeekSaved()) {
				restoreFromDB();
				if (isReload()) {
					showToastNotInternet();
				}
			} else {
				clearDataOnFragments();
				showToastNotInternet();
				showSettingsActivity();
			}
		}
	}

	private void showToastNotInternet() {
		Toast.makeText(this, R.string.not_internet, Toast.LENGTH_LONG).show();
	}

	private void showSettingsActivity() {
		if (!isShowed) {
			Intent launchPreferencesIntent = new Intent(this,
					SettingsActivity.class);
			Toast.makeText(
					getApplicationContext(),
					getResources().getString(
							R.string.cource_and_group_not_selected),
					Toast.LENGTH_SHORT).show();
			startActivityForResult(launchPreferencesIntent,
					ApplicationConstants.REQUEST_CODE_PREFERENCES);
			isShowed = true;
		}

	}

	@Override
	public void success(Intent intent) {
		if (isAsyncTaskResult(getUrl(), intent)) {
			List<B> result = intent
					.getParcelableArrayListExtra(CommonAsyncTask.RESULT);
			success(result);
		} else {
			Toast.makeText(this, "Nothing to show", Toast.LENGTH_SHORT).show();
			Log.d(TAG, "Nothing to show");
		}

	}

	protected abstract void success(List<B> result);

	protected abstract boolean isReload();

	protected abstract void clearDataOnFragments();

}
